package com.atguigu.guli.serviceedu.service.impl;

import com.atguigu.guli.serviceedu.entity.Subject;
import com.atguigu.guli.serviceedu.entity.vo.SubjectVo;
import com.atguigu.guli.serviceedu.entity.vo.SubjectNestedVo;
import com.atguigu.guli.serviceedu.mapper.SubjectMapper;
import com.atguigu.guli.serviceedu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-07-30
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public List<SubjectNestedVo> nestedList() {
        ArrayList<SubjectNestedVo> subjectNestedVoArrayList = new ArrayList<>();

        //获取一级分类数据记录
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0);
        queryWrapper.orderByAsc("sort", "id");
        List<Subject> oneSubjects = baseMapper.selectList(queryWrapper);

        //获取二级分类数据记录
        QueryWrapper<Subject> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.ne("parent_id", 0);
        queryWrapper2.orderByAsc("sort", "id");
        List<Subject> twoSubjects = baseMapper.selectList(queryWrapper2);

        //填充一级分类vo数据
        for (int i = 0; i < oneSubjects.size(); i++) {
            Subject oneSubject = oneSubjects.get(i);
            //创建一级类别vo对象
            SubjectNestedVo subjectNestedVo = new SubjectNestedVo();
            BeanUtils.copyProperties(oneSubject, subjectNestedVo);
            subjectNestedVoArrayList.add(subjectNestedVo);

            //填充二级分类vo数据
            ArrayList<SubjectVo> subjectVoArrayList = new ArrayList<>();
            for (int j = 0; j < twoSubjects.size(); j++) {
                Subject twoSubject = twoSubjects.get(j);
                if(oneSubject.getId().equals(twoSubject.getParentId())){
                    //创建二级类别vo对象
                    SubjectVo subjectVo = new SubjectVo();
                    BeanUtils.copyProperties(twoSubject, subjectVo);
                    subjectVoArrayList.add(subjectVo);
                }
            }

            subjectNestedVo.setChildren(subjectVoArrayList);
        }

        return subjectNestedVoArrayList;
    }
}
